package com.gluck.cases.boostrap.controller;

import com.gluck.cases.common.utils.enums.BizSerErrorEnum;
import com.gluck.cases.common.utils.annotations.NoScanClass;
import com.gluck.cases.app.biz.impl.TestCaseService;
import com.gluck.cases.common.utils.utils.AssertUtil;
import com.gluck.cases.core.modal.dto.TestCaseDTO;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.List;

/**
 * @ClassName TestController
 * @Desc 测试模块
 * @Author shiyongzhe
 * @Date 2022/5/24 - 9:04 下午
 **/
@RestController
@RequestMapping(value = "/test", name = "测试模块")
@NoScanClass
public class TestController {

    @Autowired
    private TestCaseService testCaseService;

    /**
     * 功能描述: 下载测试用例
     *
     * @Params []
     * @Return com.gluck.stock.base.utils.BizResult
     * @Author I`m Gluck
     * @Date 2022/5/24
     */
    @RequestMapping(value = "/cases", method = RequestMethod.GET, name = "下载测试用例")
    public void dowloadTestCase(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<TestCaseDTO> allApiData = testCaseService.getAllApiData(Collections.emptyList());
        if (allApiData.size() == 0) {
            AssertUtil.isTrue(true, BizSerErrorEnum.DOWNLOAD_ERROR);
        }
        Workbook workbook = testCaseService.downloadTestCase2Excel(allApiData);
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.reset();
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8 cases.xls");
        setFileName(request, response, "cases.xls");
        workbook.write(toClient);
        toClient.flush();
        toClient.close();
    }


    private static void setFileName(HttpServletRequest request, HttpServletResponse response, String name) throws UnsupportedEncodingException {
        String agent = request.getHeader("USER-AGENT");
        if (null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident")) {// IE浏览器
            name = java.net.URLEncoder.encode(name, "UTF8");

        } else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等浏览器
            name = new String(name.getBytes("UTF-8"), "iso-8859-1");
        }
        response.setHeader("Content-disposition", "attachment; filename=" + name);
    }

}
